package org.folio.rest.impl;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.folio.rest.impl.other.PartyUtil;
import org.folio.rest.jaxrs.model.*;
import org.folio.rest.jaxrs.resource.PartyImage;
import org.folio.rest.persist.PgUtil;
import org.folio.rest.persist.cql.CQLWrapper;
import org.folio.rest.tools.utils.ValidationHelper;
import org.folio.util.UuidUtil;

import javax.ws.rs.core.Response;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;

import static io.vertx.core.Future.succeededFuture;

/**
 * @author lee
 * @Classname PartyUploadsImpl
 * @Description TODO
 * @Date 2020/6/22 11:46
 * @Created by lee
 */
public class PartyUploadImageImpl implements PartyImage {

    private final Logger logger = LoggerFactory.getLogger("modparty");

    private static final String NOTIFY_TABLE = "party_image";

    @Override
    public void postPartyImage(String lang, UploadImage entity, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        String id = UUID.randomUUID().toString();
        List<String> fileNameList = Arrays.asList("jpeg","png","jpg","gif");
        String[] nameType = entity.getName().split("\\.");

        String string = entity.getContent();
        String base[]=string.split(",");
        String[] dataType = base[0].split("/");
        String fileType = dataType[1].split(";")[0];
        if(fileNameList.contains(nameType[1])){
          PgUtil.postgresClient(vertxContext,okapiHeaders).get("party_set", PartySetGroup.class,new String[]{"*"},PartyUtil.CQLCreate("(isDel = 0 and code == UPLOAD_FILE_SAVE_PATH)",-1,-1,"party_set"),false,false, reply-> {
                String path = "/opt/folio/uploads";
                if (reply.succeeded()){
                      List<PartySetGroup> ps = reply.result().getResults();

                      if (ps.size()>0){
                          path = ps.get(0).getContent();
                       }
                  }
                entity.setIsDel("0");
                String fileName = DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN)+"."+fileType;
                entity.setName(fileName);
                FileUtil.mkdir(path);
                File saveFilePath = new File(path+"/"+ fileName);
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(saveFilePath);
                    System.out.println();
                    Base64.decodeToStream(base[1],fileOutputStream,true);
                    entity.setContent(saveFilePath.getPath());
                    PgUtil.postgresClient(vertxContext,okapiHeaders)
                            .save(NOTIFY_TABLE,id,entity,saveReply->{
                                if (reply.succeeded()){
                                     entity.setId(id);
                                    asyncResultHandler.handle(Future.succeededFuture(PostPartyImageResponse.respond201WithApplicationJson(entity,PostPartyImageResponse.headersFor201())));
                                }else {
                                    ValidationHelper.handleError(reply.cause(),asyncResultHandler);
                                }
                            });

                }catch (Exception e){
                    ValidationHelper.handleError(e ,asyncResultHandler);
                }
            });


        }
    }

    @Override
    public void getPartyImage(String query, int offset, int limit, String lang, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
       if (StrUtil.isBlankOrUndefined(query)){
           logger.error("The query is NULL , check your request query" );
           Errors valErr = ValidationHelper.createValidationErrorMessage("query", query,
                   "Your request ID is empty, this is not allowed  ");
           asyncResultHandler.handle(succeededFuture(GetPartyImageResponse.respond401WithTextPlain(valErr)));
           return;
       }
        CQLWrapper cqlWrapper = null;
        try{
            cqlWrapper=PartyUtil.getCQL(query,limit,offset,NOTIFY_TABLE);
        }catch (Exception e){
            Errors valErr = ValidationHelper.createValidationErrorMessage("query", query,
                    "Your request query is err, this is not allowed  ");
            asyncResultHandler.handle(succeededFuture(GetPartyImageResponse.respond401WithTextPlain(valErr)));
            return;
        }
       PgUtil.postgresClient(vertxContext,okapiHeaders).
                get(NOTIFY_TABLE, ImageGroup.class,new String[]{"*"},cqlWrapper,true,false , reply->{
                      if (reply.succeeded()){
                          List<ImageGroup> list = reply.result().getResults();
                          UploadImageCollection entity = new UploadImageCollection();
                          entity.setImageGroup(list);
                          entity.setTotalRecords(reply.result().getResultInfo().getTotalRecords());
                          asyncResultHandler.handle(Future.succeededFuture(GetPartyImageResponse.respond200WithApplicationJson(entity)));
                      }else {
                          ValidationHelper.handleError(reply.cause(),asyncResultHandler);
                      }
                });

    }

    @Override
    public void getPartyImageById(String id, Map<String, String> okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {
        if (StrUtil.isBlankOrUndefined(id)){
            logger.error("The id is null , check your request id" );
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                    "Your request ID is empty, this is not allowed  ");
            asyncResultHandler.handle(succeededFuture(GetPartyImageResponse.respond401WithTextPlain(valErr)));
            return;
        }
        if (!UuidUtil.isUuid(id)){
            logger.error("The id is err , check your request id " );
            Errors valErr = ValidationHelper.createValidationErrorMessage("id", id,
                    "Your request ID is err, this is not allowed  ");
            asyncResultHandler.handle(succeededFuture(GetPartyImageResponse.respond401WithTextPlain(valErr)));
            return;
        }

        PgUtil.postgresClient(vertxContext,okapiHeaders).getById(NOTIFY_TABLE,id,UploadImage.class,reply->{
            if (reply.succeeded()){
                UploadImage image = reply.result();
                String imagePath = image.getContent();
                if (!imagePath.contains("base64")){
                    File file = new File(imagePath);
                    if (file.isFile() && file.exists()){
                        String base ="data:image/jpeg;base64,"+Base64.encode(file);
                        image.setContent(base);
                 }
                }
                asyncResultHandler.handle(succeededFuture(GetPartyImageByIdResponse.respond200WithApplicationJson(image)));
                return;
           }
            asyncResultHandler.handle(succeededFuture(GetPartyImageResponse.respond401WithTextPlain(reply.cause())));
            return;
        });
    }


}
